package com.yuanian.ecsplus.controller;

import com.yuanian.ecsplus.annotation.controller.ControllerResult;
import com.yuanian.ecsplus.bean.vo.FullDataModel;
import com.yuanian.ecsplus.cache.CacheManager;
import com.yuanian.ecsplus.context.CommonControllerContext;
import com.yuanian.ecsplus.controller.event.CommonControllerEvent;
import com.yuanian.ecsplus.enums.OperatePointType;
import com.yuanian.ecsplus.enums.OperateType;
import com.yuanian.ecsplus.model.vo.BaseVoModel;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("common")
public class CommonController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @PostMapping("/create/{apiName}")
    @Transactional
    @ControllerResult(operateType = OperateType.CREATE)
    public Object create(@PathVariable("apiName") String apiName) {
        Class clz = CacheManager.getInstance().getMetaVo(apiName).getMetaClass().getClazz();
        FullDataModel fullDataModel = new FullDataModel<>(clz);
        Map initData = new HashMap();
        this.applicationContext.publishEvent(new CommonControllerEvent(new CommonControllerContext(apiName, initData, OperateType.CREATE, OperatePointType.BEFORE)));
        Object t = fullDataModel.createOne(initData, false);
        this.applicationContext.publishEvent(new CommonControllerEvent(new CommonControllerContext(apiName, t, OperateType.CREATE, OperatePointType.AFTER)));
        return t;
    }

    @PostMapping("/insert/{apiName}")
    @Transactional
    @ControllerResult(operateType = OperateType.INSERT)
    public void insert(@PathVariable("apiName") String apiName, @RequestBody Map t) {
        BaseVoModel obj = (BaseVoModel) CacheManager.getInstance().getMetaVo(apiName).getMetaClass().toEntity(t);
        this.applicationContext.publishEvent(new CommonControllerEvent(new CommonControllerContext(apiName, t, OperateType.INSERT, OperatePointType.BEFORE)));
        obj.insert();
        this.applicationContext.publishEvent(new CommonControllerEvent(new CommonControllerContext(apiName, obj, OperateType.INSERT, OperatePointType.AFTER)));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
